package by.android.khan.authorization;

import org.scribe.builder.*;
import org.scribe.model.*;
import org.scribe.oauth.*;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.Uri;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
/**
 * @author ryz.oleg@gmail.com
 *
 */
public class OAuthHelper {
	
	private static final String url = "http://www.khanacademy.org/api/auth/request_token";
	private static final String oauth_consumer_key = "fh3ZfcKQf7LdTVAC";
	private static final String oauth_secret = "xpRKnLRUmDKzERxk";
	private static final String oauth_callback = "http://www.khanacademy.org/api/auth/default_callback?oauth_token="+oauth_consumer_key+"&oauth_secret="+oauth_secret;
    private static final Token token = new Token(oauth_consumer_key, oauth_secret);
    private static final String tag = "VkOAuthHelper";
	private static final String oauth_token = "token";
	private static final String shared_prefs = "vk_oauth_token";

	public static String getAuthURL() {
	
		OAuthService service = new ServiceBuilder()
												.provider(KhanAcademyAPI.class)
												.apiKey(oauth_consumer_key)
												.apiSecret(oauth_secret)
												.build();
		return service.getAuthorizationUrl(token);
        
	}
    
    public static void saveCredentials(Context ctx, String token) {
        Editor editor = ctx.getSharedPreferences(shared_prefs, Context.MODE_PRIVATE).edit();
        editor.putString(oauth_token, token);
        editor.commit();
}

    public static String sign(Context ctx, String url) {
        SharedPreferences savedSession = ctx.getSharedPreferences(shared_prefs, Context.MODE_PRIVATE);
        if (url.indexOf("?") > 0) {
                return url + "&access_token=" + savedSession.getString(oauth_token, null);
        } else {
                return url + "?access_token=" + savedSession.getString(oauth_token, null);
        }
}

    public static boolean isLogged(Context ctx) {
        SharedPreferences savedSession = ctx.getSharedPreferences(shared_prefs, Context.MODE_PRIVATE);
        return savedSession.getString(oauth_token, null) != null;
}

    public static void exit(Context context) {
        // Edge case: an illegal state exception is thrown if an instance of
        // CookieSyncManager has not be created. CookieSyncManager is normally
        // created by a WebKit view, but this might happen if you start the
        // app, restore saved state, and click logout before running a UI
        // dialog in a WebView -- in which case the app crashes
        try{
                CookieSyncManager cookieSyncMngr = CookieSyncManager.createInstance(context);
                CookieManager cookieManager = CookieManager.getInstance();
                cookieManager.removeAllCookie();
        } catch (Exception e) {
                // TODO: handle exception
        }
        Editor editor = context.getSharedPreferences(shared_prefs, Context.MODE_PRIVATE)
                        .edit();
        editor.clear();
        editor.commit();
}

    public static boolean isRedirect(String url) {
        return url.startsWith(oauth_callback);
}

    public static boolean proceedRedirectURL(final Activity context, String url, final Runnable success) {
        if (isRedirect(url)) {
                Uri parseUrl = Uri.parse(url);
                final String token = parseUrl.getFragment();
                if (token == null) {
                        return false;
                }
                OAuthHelper.saveCredentials(context, token.split("=")[1]);
                if (success != null) {
                        success.run();
                }
                return true;
        }
        return false;
}

	
}
